﻿#define _CRT_SECURE_NO_WARNINGS
// ↑ 将本行在代码放在第一行可以避免 scanf的报错问题（仅在VS编译器里）

//【头文件包含】
#include"SingleList.h"






//【接口函数】
/*单链表打印*/void SingleListPrint(SGLN* phead)
{
	SGLN* cur = phead;
	while (cur != NULL)
	{
		printf("%d",cur->data);
		cur = cur->next;
		if(cur != NULL)printf("->");
	}
	printf("\n");
}
/*单链表创建新空间*/SGLN* SingleListNewMember(SGLDataType x)
{
	SGLN* newnode = (SGLN*)malloc(sizeof(SGLN));
	if (newnode == NULL)
	{
		printf("malloc fail\n");
		exit(-1);
	}
	newnode->data = x;
	newnode->next = NULL;
	return newnode;
}



/*单链表尾部插入*/void SingleListPushBack(SGLN** pphead, SGLDataType x)//
{
	
	//创建节点
	SGLN* newnode=SingleListNewMember(x);
	//判断传进来的指针是否为空
	if (*pphead == NULL)
	{
		*pphead = newnode;
	}
	//不为空找到尾结点
	else
	{
		
		SGLN* tail = *pphead;
		while (tail->next != NULL)
		{
			tail = tail->next;
		}

		tail->next = newnode;
	}
}
/*单链表尾部删除*/void SingleListPopBack(SGLN** pphead)//
{
	//判断传进来的指针是否为空
	assert(*pphead != NULL);

	
	//不为空先创建临时变量
	SGLN* tail = *pphead;

	//判断是不是首个结构体
	if(tail->next!=NULL)
	{ 
		SGLN* tail_befor = NULL;
		while (tail->next != NULL)
		{
			tail_befor = tail;
			tail = tail->next;
			if (tail->next == NULL)
			{
				tail_befor->next = NULL;
			}
		}
		free(tail);
		tail = NULL;
	}
	else//如果是首个结构体那就不能去释放tail而直接释放phead的空间并将pphead置空，这样才保证修改到原指针上
	{
		free(*pphead);
		*pphead = NULL;
	}
}
/*单链表头部插入*/void SingleListPushFront(SGLN** pphead, SGLDataType x)//
{
	//创建节点
	SGLN* newnode = SingleListNewMember(x);
	//判断传进来的指针是否为空(可以省略，因为为空直接将newnode->next指向空也可以)
	/*if (*pphead == NULL)
	{
		*pphead = newnode;
	}*/
	//不为空新结构体指针成员指向原链表首结构体地址
	//else
	
		newnode->next = *pphead;
		*pphead = newnode;
	
}
/*单链表头部删除*/void SingleListPopFront(SGLN** pphead)//
{
	//判断传进来的指针是否为空
	assert(*pphead != NULL);
	//不为第一个元素指向
	SGLN* tail = *pphead;
	*pphead = tail->next;
	free(tail);
	tail = NULL;
	
}

/*单链表查找元素*/SGLN* SingleListFind(SGLN* phead, SGLDataType x)
{
	assert(phead != NULL);
	SGLN* cur = phead;
	while (cur != NULL)
	{
		if (cur->data == x)
		{
			return cur;
		}
		else
		{
			cur = cur->next;
		}
	}
	if (cur == NULL)return NULL;
}
/*单链表指定位置插入*/void SingleListInsert(SGLN** pphead, SGLN* pos, SGLDataType x)
{
	assert(pos != NULL);
	//创建节点
	SGLN* newnode = SingleListNewMember(x);
	//判断
	//判断传进来的指针和插入位置是否为同一位置
	if (*pphead == pos)
	{
		newnode->next = *pphead;
		*pphead = newnode;
	}
	else
	{
		//找pos前一位
		SGLN* posFront = *pphead;
		while (posFront->next != pos)
		{
			posFront = posFront->next;
		}
		posFront->next = newnode;
		newnode->next = pos;
	}
}
/*单链表指定位置删除*/void SingleListErase(SGLN** pphead, SGLN* pos)
{
	
}

/*单链表动态内存空间销毁*/void SingleListDestory(SGLN** pphead)
{

}
/*单链表指定位置后插入*/void SingleListInsertAfter(SGLN* pos, SGLDataType x)
{

}
/*单链表初始化*/void SingleListInit()
{

}